package com.xiaoxiao;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mzlion.core.lang.StringUtils;
import com.mzlion.easyokhttp.HttpClient;
import com.xiaoxiao.pojo.SonarRule;
import com.xiaoxiao.pojo.SonarRulesConfig;

import javax.annotation.Resources;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainApplication {
    private Map<String,String> typeMap, levelMap;
    private List<File> fileList;
    private Gson gson;

    public MainApplication() {
        // 访问地址-采用的规则-java,将返回的数据copy到resources下的java-activation.json文件里
        // http://172.21.99.65:9000/api/rules/search?languages=java&p=1&ps=500&activation=yes&qprofile=AXbb8B1jfA6lW0GcZpN8
        // 访问地址-不采用的规则-java,将返回的数据copy到resources下的java-inactivation.json文件里
        // http://172.21.99.65:9000/api/rules/search?languages=java&p=1&ps=500&activation=no&qprofile=AXbb8B1jfA6lW0GcZpN8
        // 访问地址-采用的规则-js,将返回的数据copy到resources下的js-activation.json文件里
        // http://172.21.99.65:9000/api/rules/search?languages=js&p=1&ps=500&activation=yes&qprofile=AXbb6711fA6lW0GcZpGo
        // 访问地址-不采用的规则-js,将返回的数据copy到resources下的js-inactivation.json文件里
        // http://172.21.99.65:9000/api/rules/search?languages=js&p=1&ps=500&activation=no&qprofile=AXbb6711fA6lW0GcZpGo
        // 访问地址-采用的规则-xml,将返回的数据copy到resources下的xml-activation.json文件里
        // http://172.21.99.65:9000/api/rules/search?languages=xml&p=1&ps=500&activation=yes&qprofile=AXbb67SCfA6lW0GcZo8t
        // 访问地址-不采用的规则-xml,将返回的数据copy到resources下的xml-inactivation.json文件里
        // http://172.21.99.65:9000/api/rules/search?languages=xml&p=1&ps=500&activation=no&qprofile=AXbb67SCfA6lW0GcZo8t
        gson = new Gson();
        typeMap = new HashMap();
        typeMap.put("CODE_SMELL", "坏味道");
        typeMap.put("BUG", "BUG");
        typeMap.put("VULNERABILITY", "漏洞");

        levelMap = new HashMap();
        levelMap.put("MAJOR", "主要");
        levelMap.put("CRITICAL", "重要");
        levelMap.put("MINOR", "次要");
        levelMap.put("INFO", "提醒");
        levelMap.put("BLOCKER", "阻断");

        fileList = new ArrayList<File>();

        // 首先读取根目录下是否存在config.json
        URL resourcesConfigUrl = Resources.class.getResource("/config.json");
//        File resourcesConfigFile = new File(resourcesConfigUrl.getFile());
        File expandConfig = new File("./config.json");
        if (expandConfig.exists()){
            this.readConfig(expandConfig.getAbsolutePath());
        }else if (resourcesConfigUrl!=null) {
            this.readConfig(resourcesConfigUrl.getPath());
        } else {
            String[] fileUrlList = new String[]{"/java-activation.json","/js-activation.json","/xml-activation.json"/*,
                            "/java-inactivation.json", "/js-inactivation.json", "/xml-inactivation.json"*/};
            for (String fileUrl: fileUrlList) {
                fileList.add(new File(fileUrl));
            }
        }
    }

    public static void main(String[] args) {

        MainApplication application = new MainApplication();
        application.exportExcel(application.fileList);
    }

    private void exportExcel(List<File> fileList) {
        List<SonarRule> sonarRuleList = new ArrayList<SonarRule>();
        try {
            for (File file:fileList) {
                InputStream inputStream = new FileInputStream(file);
                if (inputStream!=null) {
                    String jsonStr=IoUtil.read(inputStream, "utf-8");

                    if (JSONUtil.isJson(jsonStr)) {
                        JSONObject jsonObject = new JSONObject(jsonStr);
                        JSONArray jsonArray=JSONUtil.parseArray(jsonObject.getJSONArray("rules"));
                        if (jsonArray!=null&&jsonArray.size()>0) {
                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject ruleObj= (JSONObject) jsonArray.get(i);
                                if (ruleObj!=null) {
                                    SonarRule sonarRule = new SonarRule();

                                    String keyValue = ruleObj.getStr("key");
                                    sonarRule.setKey(keyValue);

                                    String nameValue = ruleObj.getStr("name");
                                    sonarRule.setName(nameValue);

                                    String severityValue = ruleObj.getStr("severity");
                                    sonarRule.setSeverity(levelMap.get(severityValue));

                                    String typeValue = ruleObj.getStr("type");
                                    sonarRule.setType(typeMap.get(typeValue));

                                    if (file.getName().endsWith("-inactivation.json")) {
                                        sonarRule.setAdopt("不采用");
                                        sonarRule.setReason("");
                                    } else {
                                        sonarRule.setAdopt("采用");
                                    }

                                    System.out.println(sonarRule);
                                    sonarRuleList.add(sonarRule);
                                }
                            }
                        }
                    }
                }
            }

            File outRulesFile = new File("rules.xlsx");
            if (outRulesFile.exists()&&outRulesFile.isFile()) {
                outRulesFile.delete();
            }
            // 生成Excel文件
            io.github.biezhi.excel.plus.Writer.create()
                    .headerTitle("Sonar检查清单")
                    .withRows(sonarRuleList)
                    .to(outRulesFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void readConfig(String fileName) {
        if (fileList!=null) {
            fileList.clear();
        }
        File configFile = null;
        if (StringUtils.isEmpty(fileName)) {
            configFile = new File("config.json");
        } else {
            configFile = new File(fileName);
        }
        FileReader fileReader= new FileReader(configFile, "utf-8");
        String configStr = fileReader.readString();
        List<SonarRulesConfig> configList = gson.fromJson(configStr, new TypeToken<List<SonarRulesConfig>>(){}.getType());
        for (int i = 0; i < configList.size(); i++) {
            SonarRulesConfig sonarRulesConfig = configList.get(i);
            String type = sonarRulesConfig.getType();
            List<SonarRulesConfig.ConfigDataObj> data = sonarRulesConfig.getData();
            if (data!=null) {
                for (SonarRulesConfig.ConfigDataObj dataObj:data
                     ) {
                    String configName = dataObj.getName();
                    String configUrl = dataObj.getUrl();

                    if (configUrl!=null) {
                        File saveFile = new File(new StringBuilder("./").append(configName).append("-").append(type).append(".json").toString());
                        HttpClient.get(configUrl).asFile(saveFile);
                        fileList.add(saveFile);
                    }
                }
            }
        }
    }
}
